import axios from "axios";
import env from "../config/env";
import Vue from "vue";

let util = {};
util.title = function (title) {
    title = title || 'iView admin';
    window.document.title = title;
};

const ajaxUrl = env === 'development'
    ? '/api'
    : env === 'production'
        ? 'https://www.url.com'
        : 'https://debug.url.com';

const springbootadminUrl = env === 'development'
    ? 'http://localhost:1300'
    : env === 'production'
        ? 'https://www.url.com'
        : 'https://debug.url.com';

util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 30000
});
util.springbootadminUrl = springbootadminUrl;

util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function (itAccess, currentAccess) {
    if (typeof itAccess === 'object' && itAccess.isArray()) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

util.getRouterObjByName = function (routers, name) {
    let routerObj = {};
    routers.forEach(item => {
        if (item.name === 'otherRouter') {
            item.children.forEach((child, i) => {
                if (child.name === name) {
                    routerObj = item.children[i];
                }
            });
        } else {
            if (item.children.length === 1) {
                if (item.children[0].name === name) {
                    routerObj = item.children[0];
                }
            } else {
                item.children.forEach((child, i) => {
                    if (child.name === name) {
                        routerObj = item.children[i];
                    }
                });
            }
        }
    });
    return routerObj;
};

util.handleTitle = function (vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function (vm, name) {
    let title = '';
    let isOtherRouter = false;
    vm.$store.state.routers.forEach(item => {
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {
                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.routers, 'home_index')),
                path: '',
                name: 'home_index'
            }
        ];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        currentPathArr = [
            {
                title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.routers, 'home_index')),
                path: '/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.routers.filter(item => {
            if (item.children.length <= 1) {
                return item.children[0].name === name;
            } else {
                let i = 0;
                let childArr = item.children;
                let len = childArr.length;
                while (i < len) {
                    if (childArr[i].name === name) {
                        return true;
                    }
                    i++;
                }
                return false;
            }
        })[0];
        if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '',
                    name: 'home_index'
                }
            ];
        } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: name
                }
            ];
        } else {
            let childObj = currentPathObj.children.filter((child) => {
                return child.name === name;
            })[0];
            currentPathArr = [
                {
                    title: '首页',
                    path: '/home',
                    name: 'home_index'
                },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: childObj.title,
                    path: currentPathObj.path + '/' + childObj.path,
                    name: name
                }
            ];
        }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) {  // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        tag = tag.children ? tag.children[0] : tag;
        if (argu) {
            tag.argu = argu;
        }
        if (query) {
            tag.query = query;
        }
        vm.$store.commit('increateTag', tag);
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

/**
 * 两层的树
 * @param arr
 * @returns {Array}
 */
util.menuTree = arr => {
    let result = [];
    arr.forEach(function (value, index, arr) {
        value.title = value.value; // 标题,前端代码用title展示,所以name->title
        if (!value.pid) {
            result.push(value);
        }
    });
    arr.forEach(function (value, index, arr) {
        if (value.pid) {
            for (let i = 0; i < result.length; i++) {
                if (result[i].id === value.pid) {
                    result[i].children = result[i].children || [];
                    result[i].children.push(value);
                    break;
                }
            }
        }
    });
    return result;
};

/**
 * list搜索数据
 * @param cnf
 */
util.listSearch = cnf => {
    let params = cnf.params || {};
    let url = cnf.url || "";
    let list = cnf.list || {};
    list.table = list.table || {};
    list.page = list.page || {};

    list.table.loading = true;

    util.post({
        url: url,
        params: params,
        ajaxSuccess: (response) => {
            let context = response.data;
            let pageinfo = context.data;
            list.table.data = pageinfo.list;
            // list.page.current = pageinfo.pageNum;
            list.page.total = pageinfo.total;
            if (list.page.total > 0 && !list.table.data.length) {
                params.pageNum = 1;
                util.listSearch(cnf);
            } else {
                list.table.loading = false;
            }
        },
        ajaxFail: (response) => {
            list.table.loading = false;
        }
    });
};

/**
 * 通用的post
 * @param cnf
 */
util.post = (cnf) => {
    let url = cnf.url || "";
    let params = util.params(cnf.params || {}, cnf.data || {});
    util.ajax.post(url, params).then(response => {
        let context = response.data;
        if (!context.success) {
            Vue.prototype.$Message.error({
                content: context.message || "请求成功,但是返回数据存在错误",
                duration: 10,
                closable: true
            });
            return;
        }
        if (cnf.ajaxSuccess) {
            cnf.ajaxSuccess.apply(this, [response]);
        }
    }, response => {
        Vue.prototype.$Message.error({
            content: "请求失败",
            duration: 10,
            closable: true
        });
        if (cnf.ajaxFail) {
            cnf.ajaxFail.apply(this, [response]);
        }
    });
};

/**
 * 封装JS对象到contextDto格式
 * @param params
 * 原装的JS参数
 */
util.params = (requestParams, requestData) => ({
    requestParams: requestParams,
    requestData: requestData
});

/**
 * datagrid的查询参数
 * @type {{pageSize: number, pageNum: number, count: boolean}}
 */
util.queryParams = {
    pageSize: 10,
    pageNum: 1,
    count: true
};

util.copyProps = (a, b) => {
    for (let i in b) {
        a[i] = b[i];
    }
};

util.commonAjaxSuccess = (response) => {
    let context = response.data;
    Vue.prototype.$Message.success({
        content: context.message || "操作成功",
        duration: 4,
        closable: true
    });
};

util.deepClone = (obj) => {
    let proto = Object.getPrototypeOf(obj);
    return Object.assign({}, Object.create(proto), obj);
};

util.formatDate = (conf) => {
    var d = conf.date;
    var fmt = conf.format || "yyyy-MM-dd hh:mm:ss";
    var o = {
        "M+": d.getMonth() + 1, // 月份
        "d+": d.getDate(), // 日
        "h+": d.getHours(), // 小时
        "m+": d.getMinutes(), // 分
        "s+": d.getSeconds(), // 秒
        "q+": Math.floor((d.getMonth() + 3) / 3), // 季度
        "S": d.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

util.setReactiveField = (obj, field, value) => {
    if (obj[field] === undefined) {
        Vue.set(obj, field, value);
    }
}

export default util;
